<template>
    <div class="configure-content-box">
        <div class="configure-title">
            <span class="time">最近修改时间为：{{ lately_update_time }}</span>

            <div>
                <el-button plain @click="showConfigureAdvanced">高级设置</el-button>
                <el-button type="primary" @click="showAddConfigure">新增线索属性</el-button>
            </div>
        </div>

        <el-table
            id="tableRef"
            ref="tableRef"
            :row-key="getRowKey"
            class="configure-table-box"
            stripe
            header-row-class-name="table_header_title"
            :data="tableList">
            <el-table-column width="55">
                <template #default>
                    <img src="@/assets/customer/sort-icon.png" class="sortImg" alt="" />
                </template>
            </el-table-column>
            <el-table-column prop="name" label="属性名">
                <template #default="{ row }">
                    {{ row.name || '--' }}
                </template>
            </el-table-column>
            <el-table-column prop="typeName" label="格式"></el-table-column>
            <el-table-column label="选项内容">
                <template #default="{ row }">
                    {{ row.attr_val_name }}
                </template>
            </el-table-column>
            <el-table-column prop="weight" label="排序"></el-table-column>
            <el-table-column label="状态">
                <template #default="{ row }">
                    {{ row.is_enable == 1 ? '已开启' : '未开启' }}
                </template>
            </el-table-column>
            <el-table-column label="类型">
                <template #default="{ row }">
                    {{ row.is_system == 1 ? '系统' : '自定义' }}
                </template>
            </el-table-column>
            <el-table-column label="必填">
                <template #default="{ row }">
                    {{ row.is_required == 1 ? '否' : '是' }}
                </template>
            </el-table-column>
            <el-table-column prop="created_name" label="创建人"></el-table-column>
            <el-table-column label="创建时间" width="200">
                <template #default="{ row }">
                    {{ row.created_at || '--' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="300px">
                <template #default="{ row }">
                    <el-button v-if="row.system_code != 'mobile'" size="small" @click="openOrClose(row)">{{
                        row.is_enable == 1 ? '关闭' : '开启'
                    }}</el-button>
                    <template v-if="row.is_system !== 1">
                        <el-button size="small" @click="showEdit(row)">编辑</el-button>
                        <el-button size="small" @click="del(row)">删除</el-button>
                    </template>
                </template>
            </el-table-column>
            <template #empty>
                <img class="emty_img" src="@/assets/noData.png" alt="" />
                <div class="emty_title">{{ '暂无数据' }}</div>
            </template>
        </el-table>

        <!-- <ZWPagination ref="PaginationRef" @submit="getFile" /> -->
        <AddConfigure ref="AddConfigureRef" @save="getTableList" />
        <ConfigureAdvanced ref="ConfigureAdvancedRef" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue';
import { attrList, updateStatus, attrDel, attrSort } from '@/api/customer/clubManage/clueSetting';
import { ElMessage, ElMessageBox } from 'element-plus';
import Sortable from 'sortablejs';
import ConfigureAdvanced from './ConfigureAdvanced.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import AddConfigure from './AddConfigure.vue';
import { useStore } from '@/store';
import { getSetionId, tableH, reSize } from '@/utils/utils';

const pageParam = { page: 1, page_size: 15 };
const tableData = ref([]);
const AddConfigureRef = ref({});
const showTable = ref(true);
const ConfigureAdvancedRef = ref(null);
const PaginationRef = ref({});
const store = useStore();
const tableList = ref([{ attr_id: 1 }, { attr_id: 2 }]);
const lately_update_time = ref('');

const typeList = reactive([
    { label: '单行文本', value: 'textbox' },
    { label: '多行文本', value: 'textarea' },
    { label: '单选', value: 'select' },
    { label: '多选', value: 'muti_select' },
    { label: '日期', value: 'date' },
    { label: '手机号', value: 'mobile' },
    { label: '邮箱', value: 'email' },
    { label: '区域', value: 'pca' },
    { label: '图片', value: 'picture' }
]);
const tabH = ref('500px');
// 表格的自适应高度
const getTableH = (val?: boolean) => {
    const h = parseInt(tableH('.configure-table-box'));
    tabH.value = h - 120 + 'px';
};

// 排序的方法
const setSortableFun = () => {
    let nowIndex;
    let copyTableList;
    nextTick(() => {
        const SortableBox = new Sortable(
            document.querySelector('#tableRef').querySelector('.el-table__body-wrapper tbody'),
            {
                animation: 100,
                sort: true,
                delay: 0,
                delayOnTouchOnly: false,
                onChoose: function (evt: any) {
                    nowIndex = evt.oldIndex;
                },
                onEnd: (evt: any) => {
                    copyTableList = JSON.parse(JSON.stringify(tableList.value));
                    const data = copyTableList.splice(evt.oldIndex, 1)[0];
                    copyTableList.splice(evt.newIndex, 0, data);
                    let next_id, pre_id;
                    if (copyTableList[evt.newIndex - 1]) {
                        pre_id = copyTableList[evt.newIndex - 1].attr_id;
                    }
                    if (copyTableList[evt.newIndex + 1]) {
                        next_id = copyTableList[evt.newIndex + 1].attr_id;
                    }
                    const arr: any = [];
                    copyTableList.forEach((item: any, index: number) => {
                        arr.push({ id: item.id, sort: index + 1 });
                    });
                    attrSort({ sorts: arr }).then((r: any) => {
                        getTableList();
                    });
                }
            }
        );
    });
};
// 获取列表数据
const getTableList = () => {
    attrList({}).then((r: any) => {
        lately_update_time.value = r.lately_update_time || '--';
        showTable.value = false;
        tableList.value = r.data.map((item: object) => {
            if (item.type) {
                const index = typeList.findIndex(it => {
                    return it.value == item.type;
                });
                item.typeName = '';
                if (index > -1) {
                    item.typeName = typeList[index].label;
                }
            }
            return item;
        });
        setTimeout(() => {
            showTable.value = true;
            nextTick(() => {
                setSortableFun();
            });
        });
        getTableH();
    });
};
nextTick(() => {
    getTableList();
});
// 打开弹窗
const showConfigureAdvanced = () => {
    ConfigureAdvancedRef.value.appDialog.visible = true;
};
// 分页
// const getFile = (val: any) => {
//   pageParam.page = val.page
//   pageParam.page_size = val.page_size || pageParam.page_size
//   getTableList()
// }
// 开启或关闭
const openOrClose = async (item: object) => {
    await updateStatus({ attr_id: item.id, is_enable: item.is_enable == 1 ? 2 : 1 });
    getTableList();
    ElMessage.success('操作成功');
};
// 新建
const showAddConfigure = () => {
    AddConfigureRef.value.appDialog.visible = true;
    AddConfigureRef.value.titles = '新增线索属性';
};
// 编辑
const showEdit = (val: object) => {
    AddConfigureRef.value.appDialog.visible = true;
    AddConfigureRef.value.appDialog.editData = val;
    AddConfigureRef.value.titles = '编辑线索属性';
};
// 删除
const del = async (v: any) => {
    ElMessageBox.confirm(`删除后，线索该字段的属性也将被删除，请慎重`, `删除【${v.name}】`, {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if (!v.id) {
            ElMessage.error('当前数据异常，请稍后再试');
            getTableList();
            return;
        }
        await attrDel({ attr_id: v.id });
        getTableList();
        ElMessage.success('删除成功');
    });
};
const getRowKey = (row: any) => {
    return row.id;
};
onMounted(() => {
    reSize(getTableH);
});
</script>

<style lang="scss" scoped>
.sortImg {
    width: 13px;
    height: 11px;
}

.configure-content-box {
    height: calc(100vh - 246px);
    display: flex;
    flex-direction: column;

    :deep(.el-table) {
        flex: 1;

        .el-table__empty-block {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    }

    .configure-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;

        .time {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #33302d;
        }
    }

    .pageLimit-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 82px;

        .total-box {
            width: 200px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #33302d;

            span {
                color: #ff6b00;
            }
        }
    }

    .configure-table-box {
        border: 1px solid #eaeaea;

        .btn {
            width: 80px;
            height: 24px;
            background: #fff;
            border-radius: 2px;
            border: 1px solid #eaeaea;
            text-align: center;
            line-height: 24px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #33302d;
            cursor: pointer;
            display: inline-block;
            vertical-align: middle;
            margin-right: 10px;
        }
    }
}
</style>

<style>
.configure-content-box .el-tabs__item {
    color: #969696;
}

.configure-content-box .is-active {
    color: #ff6b00;
}
</style>
